// 功能部分的代码 

import React, { ChangeEvent, useRef } from 'react';
import axios from 'axios'
import Button from '../button'


export interface UploadProps {
    action: string,
    onProgress?: (percentage: number, file: File) => void
    onSuccess?: (data: any, file: File) => void
    onError?: (err: any, file: File) => void
    //这个回调函数用于 在上传之前处理一下名字或格式或检查一下大小之类的
    beforeUpload?: (file: File) => boolean | Promise<File>
}

const Upload: React.FC<UploadProps> = (props) => {
    // props
    const { action, onProgress, onSuccess, onError, beforeUpload } = props
    // state -ref
    const inputRef = useRef<HTMLInputElement>(null)
    // methods
    const handleBtnClick = () => {
        if (inputRef.current) {
            inputRef.current.click()
        }
    }
    const handleFile = (e: ChangeEvent<HTMLInputElement>) => {
        const files = e.target.files
        if (!files) return
        uploadFiles(files)
        if (inputRef.current) {
            inputRef.current.value = ''
        }
    }
    const uploadFiles = (files: FileList) => {
        let postFiles = Array.from(files)
        postFiles.forEach(file => {
            // 没有传回调函数就不管了直接往下执行 
            if (!beforeUpload) {
                post(file)
            } else {
                // 传了的情况 
                const result = beforeUpload(file) //拿到处理后的结果 ---有两种情况：布尔 或 promise文件
                if (result && result instanceof Promise) {
                    result.then(processedFile => {
                        post(processedFile)
                    })
                } else if (result !== false) { //这种就是处理文件大小 大于好多kb就外面弹窗不让里面执行
                    post(file)
                }
            }
        })
    }
    const post = (file: File) => {
        //通过FormData构造函数创建一个空对象
        const formData = new FormData() //怎么搞出了一个map类型
        //可以通过append()方法来追加数据
        formData.append(file.name, file)
        //通过get方法对值进行读取--set方法对值进行设置
        // console.log(formData.get(file.name,));
        // 发送请求
        axios.post(action, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: (e) => { //axios自带的
                let percentage = Math.round((e.loaded * 100) / e.total) || 0;
                if (percentage < 100) {
                    // 触发回调函数--生命周期函数 
                    onProgress && onProgress(percentage, file)
                }
            }
        }).then(res => {
            onSuccess && onSuccess(res.data, file)
        }).catch(err => {
            onError && onError(err, file)
        })
    }


    return (
        <div className='viking-upload-component'>
            <Button btnType='primary' onClick={handleBtnClick}>Upload File</Button>
            <input className='viking-file-input' style={{ display: 'none' }}
                type='file' ref={inputRef} onChange={handleFile} />
        </div>
    )
}



export default Upload;